package cn.lili.controller.im;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.setting.Setting;
import cn.lili.cache.Cache;
import cn.lili.config.OssProperties;
import cn.lili.exception.ServiceException;
import cn.lili.result.ResultCode;
import cn.lili.result.ResultMessage;
import cn.lili.result.ResultUtil;
import cn.lili.security.AuthUser;
import cn.lili.security.UserContext;
import cn.lili.security.enums.UserEnums;
import cn.lili.utils.Base64DecodeMultipartFile;
import cn.lili.utils.CommonUtil;
import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.InputStream;
import java.util.Date;
import java.util.Objects;

/**
 * 文件上传接口
 *
 * @author Chopper
 * @since 2020/11/26 15:41
 */
@Slf4j
@RestController
@Api(tags = "文件上传接口")
@RequestMapping("/common/common/upload")
public class UploadController {
    @Autowired
    private OssProperties ossProperties;
    @ApiOperation(value = "文件上传")
    @PostMapping(value = "/file")
    public ResultMessage<Object> upload(MultipartFile file,
                                        String base64,@RequestParam String directoryPath) {
        AuthUser authUser = UserContext.getAuthUser();
        //如果用户未登录，则无法上传图片
        if (authUser == null) {
            throw new ServiceException(ResultCode.USER_AUTHORITY_ERROR);
        }
        if (file == null) {
            throw new ServiceException(ResultCode.FILE_NOT_EXIST_ERROR);
        }

        if (CharSequenceUtil.isEmpty(file.getContentType())) {
            throw new ServiceException(ResultCode.IMAGE_FILE_EXT_ERROR);
        }

        if (!CharSequenceUtil.containsAny(Objects.requireNonNull(file.getContentType()).toLowerCase(), "image", "video")) {
            throw new ServiceException(ResultCode.FILE_TYPE_NOT_SUPPORT);
        }

        if (CharSequenceUtil.isNotBlank(base64)) {
            //base64上传
            file = Base64DecodeMultipartFile.base64Convert(base64);
        }
        String fileKey = CommonUtil.rename(Objects.requireNonNull(file.getOriginalFilename()));
        try {
            //上传至第三方云服务或服务器
            fileKey =  directoryPath + "/" + fileKey;
            //上传至第三方云服务或服务器
            //构造一个带指定 Region 对象的配置类
            Configuration cfg = new Configuration(Region.huadong());  //根据自己的对象空间的地址选（华为）
            //...其他参数参考类注释
            UploadManager uploadManager = new UploadManager(cfg);
            //默认不指定key的情况下，以文件内容的hash值作为文件名
            byte[] uploadBytes = file.getBytes();
            Auth auth = Auth.create(ossProperties.getAccessKey(), ossProperties.getSecretKey());
            String upToken = auth.uploadToken(ossProperties.getBucket());
            Response response = uploadManager.put(uploadBytes, fileKey, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);
            return ResultUtil.data(ossProperties.getResourcesUrl()+"/"+fileKey);
        } catch (Exception e) {
            log.error("文件上传失败", e);
            throw new ServiceException(ResultCode.OSS_EXCEPTION_ERROR);
        }
    }
}
